<script>
  import dayjs from "dayjs";
  import { store } from "./store";
  import TodoForm from "./components/TodoForm.svelte";
  import TodoList from "./components/TodoList.svelte";

  const today = dayjs().format("YYYY/MM/DD");
  let mode = localStorage.getItem("__THEME_MODE__");

  if (mode && mode === "dark") {
    const el = document.documentElement;
    el.classList.add("mode-dark");
  }

  store.subscribe(todos => {
    localStorage.setItem("__TODOS__", JSON.stringify(todos));
  });

  function todoFormSubmit(event) {
    store.createTodo(event.detail);
  }

  function deleteTodo(event) {
    const result = window.confirm("确定删除此条待办吗？");
    if (result) {
      store.deleteTodo(event.detail);
    }
  }

  function toggleTodo(event) {
    store.toggleTodo(event.detail);
  }

  function toggleTheme() {
    const el = document.documentElement;
    const isDarkMode = el.classList.contains("mode-dark");
    el.classList.toggle("mode-dark");

    if (!isDarkMode) {
      localStorage.setItem("__THEME_MODE__", "dark");
      mode = "dark";
    } else {
      localStorage.setItem("__THEME_MODE__", "light");
      mode = "light";
    }
  }
</script>

<div class="min-h-screen bg-gray-100 dark:bg-gray-900">
  <div class="max-w-xl mx-auto p-4">
    <!-- <h1
      class="pt-4 text-3xl font-bold text-gray-500 dark:text-gray-700
      text-center uppercase">
      Svelte+Tailwindcss
      <br />
      今日待办
    </h1> -->
    <div class="flex justify-between items-center pt-2 pb-6">
      <p class="text-gray-500 dark:text-gray-700 font-bold">今天是 {today}</p>
      <button
        on:click={toggleTheme}
        class="ml-2 px-2 py-1 text-xs bg-gray-300 text-gray-600 rounded
        dark:bg-gray-800 dark:text-gray-500 focus:outline-none">
        {#if mode === 'dark'}亮色主题{:else}暗色主题{/if}
      </button>
    </div>
    <TodoForm on:todoFormSubmit={todoFormSubmit} />
    {#if $store.length > 0}
      <TodoList
        todos={$store}
        on:deleteTodo={deleteTodo}
        on:toggleTodo={toggleTodo} />
    {:else}
      <p class="py-8 text-center text-gray-400 text-xl dark:text-gray-700">
        暂无待办
      </p>
    {/if}
  </div>
</div>
